package com.aroura.util;

import us.codecraft.webmagic.model.formatter.ObjectFormatter;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DateStringFormatter implements ObjectFormatter<String> {
    private String template;

    @Override
    public String format(String rawDate) throws Exception {
        String publishTime = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        Pattern p = Pattern.compile("^\\d{4}-\\d{2}-\\d{2}$");
        Matcher matcher = p.matcher(rawDate);
        if (matcher.matches()) {
            publishTime = rawDate;
        } else if (rawDate.contains("天")) {
            int days = Integer.parseInt(rawDate.split(":")[1].trim().split("天")[0].trim());
            cal.add(Calendar.DAY_OF_MONTH, -days);
            publishTime = sdf.format(cal.getTime());
        } else {
            publishTime = sdf.format(cal.getTime());
        }
        return publishTime;
    }

    @Override
    public Class<String> clazz() {
        return String.class;
    }

    @Override
    public void initParam(String[] extra) {
        this.template = extra[0];
    }
}
